package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"runtime"
	"strings"
	"syscall"

	appmonitor "gitee.com/eehut/appmonitor-go"
	"gitee.com/eehut/appmonitor-go/monitor"

	_ "net/http/pprof"
)

var (
	processes    string
	influxAddr   string
	dbName       string
	period       int
	saveToDb     bool
	printHelp    bool
	printVersion bool
)

func init() {

	flag.IntVar(&period, "i", 10, "Set polling `period` in seconds")
	flag.BoolVar(&saveToDb, "d", false, "Save data to database(influxdb only)")
	flag.StringVar(&processes, "p", "", "Set `processes` for monitor")
	flag.StringVar(&influxAddr, "u", "http://localhost:8086", "Output data to influxdb with `url`")
	flag.StringVar(&dbName, "n", "appmon", "Set database `name`")
	flag.BoolVar(&printHelp, "h", false, "Print this help")
	flag.BoolVar(&printVersion, "v", false, "Print version")
}

func main() {

	flag.Parse()

	if printHelp {
		flag.Usage()

		os.Exit(0)
	} else if printVersion {
		fmt.Printf("%s\n", appmonitor.Version)
		os.Exit(0)
	}

	// init signals
	chExit := make(chan bool)
	chSignal := make(chan os.Signal, 1)
	signal.Notify(chSignal, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR1 /*, syscall.SIGUSR2*/)

	// catch signals
	go func() {
		for {
			select {
			case s := <-chSignal:
				fmt.Printf("Receive Signal:%d\n", s)

				if s == syscall.SIGINT || s == syscall.SIGTERM {
					chExit <- true
				} else if s == syscall.SIGUSR1 {
					fmt.Printf("do runtime.GC()")
					runtime.GC()
				}
			}
		}
	}()

	// connect to db if ok
	if saveToDb {

		err := monitor.ConnectToInfluxdb(influxAddr, dbName)
		if err != nil {
			fmt.Printf("Connect to influxdb failed:%v\n", err)
		} else {

			fmt.Printf("Add influxdb callback handle\n")
			monitor.AddHandle(monitor.HandleInfluxdb)
		}
	}

	// set monitor processes
	if len(processes) > 0 {
		items := strings.Split(processes, ",")

		if len(items) > 0 {
			monitor.SetMonitorProcess(items)
		}
	}

	// start it
	monitor.Start(period)
	/*
		go func() {
			http.ListenAndServe(":8999", nil)
		}()
	*/
	// wait for exit
	<-chExit
	monitor.Stop()

	fmt.Println("Byebye!!!")
}
